// pages/settings/settings.js
Page({
  data: {
    // 用户信息
    userInfo: {
      name: '',
      age: '',
      gender: '',
      avatarUrl: ''
    },
    
    // 单位设置
    bloodPressureUnits: ['mmHg', 'kPa'],
    bloodPressureUnitIndex: 0,
    heartRateUnits: ['次/分钟', 'bpm'],
    heartRateUnitIndex: 0,
    
    // 对话框状态
    showClearDialog: false,
    showToast: false,
    toastText: '',
    toastIcon: ''
  },

  onLoad() {
    // 加载用户设置
    this.loadSettings();
    
    // 加载用户信息
    this.loadUserInfo();
  },

  // 加载用户设置
  loadSettings() {
    const settings = wx.getStorageSync('settings') || {};
    
    // 设置血压单位
    const bloodPressureUnitIndex = settings.bloodPressureUnit === 'kPa' ? 1 : 0;
    
    // 设置心率单位
    const heartRateUnitIndex = settings.heartRateUnit === 'bpm' ? 1 : 0;
    
    this.setData({
      bloodPressureUnitIndex: bloodPressureUnitIndex,
      heartRateUnitIndex: heartRateUnitIndex
    });
  },

  // 加载用户信息
  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo') || {};
    
    this.setData({
      userInfo: userInfo
    });
  },

  // 选择头像
  chooseAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFiles[0].tempFilePath;
        
        // 保存头像路径
        const userInfo = {
          ...this.data.userInfo,
          avatarUrl: tempFilePaths
        };
        
        this.setData({
          userInfo: userInfo
        });
        
        // 保存到本地存储
        wx.setStorageSync('userInfo', userInfo);
        
        // 显示成功提示
        this.showToast('头像更新成功', '/images/success.png');
      }
    });
  },

  // 导航到个人信息页面
  navigateToPersonalInfo() {
    wx.navigateTo({
      url: '/pages/settings/personal-info/personal-info'
    });
  },

  // 血压单位变化
  onBloodPressureUnitChange(e) {
    const index = e.detail.value;
    const unit = this.data.bloodPressureUnits[index];
    
    this.setData({
      bloodPressureUnitIndex: index
    });
    
    // 保存到设置
    const settings = wx.getStorageSync('settings') || {};
    settings.bloodPressureUnit = unit;
    wx.setStorageSync('settings', settings);
    
    // 通知其他页面单位已更改
    getApp().globalData.bloodPressureUnit = unit;
  },

  // 心率单位变化
  onHeartRateUnitChange(e) {
    const index = e.detail.value;
    const unit = this.data.heartRateUnits[index];
    
    this.setData({
      heartRateUnitIndex: index
    });
    
    // 保存到设置
    const settings = wx.getStorageSync('settings') || {};
    settings.heartRateUnit = unit;
    wx.setStorageSync('settings', settings);
    
    // 通知其他页面单位已更改
    getApp().globalData.heartRateUnit = unit;
  },

  // 备份数据
  backupData() {
    // 准备导出数据
    const exportData = {
      exportTime: this.formatDateTime(new Date()),
      bloodPressureRecords: wx.getStorageSync('bloodPressureRecords') || [],
      medicationRecords: wx.getStorageSync('medicationRecords') || [],
      settings: wx.getStorageSync('settings') || {},
      userInfo: wx.getStorageSync('userInfo') || {}
    };
    
    // 转换为JSON字符串
    const jsonData = JSON.stringify(exportData, null, 2);
    
    // 保存到本地文件
    const fileName = `血压用药记录备份_${this.formatDateTime(new Date(), 'yyyyMMddHHmmss')}.json`;
    
    // 调用文件系统API保存文件
    wx.getFileSystemManager().writeFile({
      filePath: `${wx.env.USER_DATA_PATH}/${fileName}`,
      data: jsonData,
      encoding: 'utf8',
      success: () => {
        // 保存成功后提供分享/保存到相册选项
        wx.showModal({
          title: '备份成功',
          content: `数据已备份至: ${fileName}`,
          confirmText: '分享备份',
          cancelText: '我知道了',
          success: (res) => {
            if (res.confirm) {
              // 分享文件
              wx.shareFileMessage({
                filePath: `${wx.env.USER_DATA_PATH}/${fileName}`,
                fileName: fileName,
                success: () => {
                  this.showToast('分享成功', '/images/success.png');
                },
                fail: () => {
                  this.showToast('分享失败', '/images/error.png');
                }
              });
            }
          }
        });
      },
      fail: (err) => {
        console.error('备份失败:', err);
        this.showToast('备份失败', '/images/error.png');
      }
    });
  },

  // 恢复数据
  restoreData() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['json'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].path;
        
        // 读取文件内容
        wx.getFileSystemManager().readFile({
          filePath: tempFilePath,
          encoding: 'utf8',
          success: (res) => {
            try {
              const backupData = JSON.parse(res.data);
              
              // 验证备份数据格式
              if (backupData.bloodPressureRecords && backupData.medicationRecords) {
                // 保存数据到本地存储
                wx.setStorageSync('bloodPressureRecords', backupData.bloodPressureRecords);
                wx.setStorageSync('medicationRecords', backupData.medicationRecords);
                
                // 如果有设置和用户信息也一并恢复
                if (backupData.settings) {
                  wx.setStorageSync('settings', backupData.settings);
                  this.loadSettings(); // 重新加载设置
                }
                
                if (backupData.userInfo) {
                  wx.setStorageSync('userInfo', backupData.userInfo);
                  this.loadUserInfo(); // 重新加载用户信息
                }
                
                // 显示成功提示
                this.showToast('恢复成功', '/images/success.png');
                
                // 延迟后刷新页面
                setTimeout(() => {
                  wx.reLaunch({
                    url: '/pages/index/index'
                  });
                }, 1500);
              } else {
                this.showToast('备份文件格式不正确', '/images/error.png');
              }
            } catch (e) {
              console.error('解析备份文件失败:', e);
              this.showToast('解析备份文件失败', '/images/error.png');
            }
          },
          fail: (err) => {
            console.error('读取备份文件失败:', err);
            this.showToast('读取备份文件失败', '/images/error.png');
          }
        });
      },
      fail: () => {
        this.showToast('取消选择', '/images/info.png');
      }
    });
  },

  // 确认清除数据
  confirmClearData() {
    this.setData({
      showClearDialog: true
    });
  },

  // 取消清除数据
  cancelClearData() {
    this.setData({
      showClearDialog: false
    });
  },

  // 清除所有数据
  clearAllData() {
    // 清除所有记录数据
    wx.removeStorageSync('bloodPressureRecords');
    wx.removeStorageSync('medicationRecords');
    
    // 保留设置和用户信息，但重置提醒相关设置
    const settings = wx.getStorageSync('settings') || {};
    if (settings) {
      settings.reminderEnabled = true;
      settings.reminderTime = '08:00';
      wx.setStorageSync('settings', settings);
    }
    
    // 关闭对话框
    this.setData({
      showClearDialog: false
    });
    
    // 显示成功提示
    this.showToast('所有记录已清除', '/images/success.png');
    
    // 延迟后刷新页面
    setTimeout(() => {
      wx.reLaunch({
        url: '/pages/index/index'
      });
    }, 1500);
  },

  // 显示关于信息
  showAbout() {
    wx.showModal({
      title: '关于血压用药记录',
      content: '血压用药记录小程序是一款帮助用户记录血压数据和用药情况的健康管理工具。\n\n版本: v1.0.0',
      showCancel: false,
      confirmText: '我知道了'
    });
  },

  // 显示帮助信息
  showHelp() {
    wx.navigateTo({
      url: '/pages/settings/help/help'
    });
  },

  // 提醒设置保存成功回调
  onReminderSettingsSaved() {
    this.showToast('提醒设置已更新', '/images/success.png');
  },

  // 显示提示框
  showToast(text, icon) {
    this.setData({
      showToast: true,
      toastText: text,
      toastIcon: icon
    });
    
    // 2秒后自动关闭
    setTimeout(() => {
      this.setData({
        showToast: false
      });
    }, 2000);
  },

  // 格式化日期时间
  formatDateTime(date, format) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();
    
    // 补零函数
    const padZero = num => num < 10 ? `0${num}` : num;
    
    if (format === 'yyyyMMddHHmmss') {
      return `${year}${padZero(month)}${padZero(day)}${padZero(hours)}${padZero(minutes)}${padZero(seconds)}`;
    }
    
    return `${year}-${padZero(month)}-${padZero(day)} ${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
  }
})